<?php

namespace App\Http\Middleware\CallingCards;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Support\AppletEncrypt;
use Closure;
use Illuminate\Http\Request;

class WechatAppletAuth
{
    const RMS_ENCRYPT_KEY = 'base64:tBvmm3XDYHp5HJBN2ppfRBZVbvSOzTdUmUKMbUnqpuU=';// rms加密时key

    /**
     * 验证用户在服务号网页上是否登录（在RMS代码中小程序-用户登录 platformId-6）
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (config('app.env') != 'dev') {
            //从header获取token值
            $token = $request->header('APPLET-TOKEN');
            if (!$token) {
                throw new ResponseHttpException(BaseErrorCode::$TOKEN_NOT_EXIST);
            }
            //检查token是否是小程序平台生成
            try {
                $decryptData = AppletEncrypt::getInstance()->decryptData($token, self::RMS_ENCRYPT_KEY);
            } catch (\Exception $exception) {
                throw new ResponseHttpException(BaseErrorCode::$TOKEN_ERROR_EXIST);
            }

            //检查token是否失效,如果失效重新登陆
            AppletEncrypt::getInstance()->checkInvalidToken($token, self::RMS_ENCRYPT_KEY);
            //检查token
            AppletEncrypt::getInstance()->checkExpireToken($token, self::RMS_ENCRYPT_KEY);

            $request->unionid = $decryptData['unionid'] ?? '';
            if (!$request->unionid) {
                throw new ResponseHttpException(BaseErrorCode::$TOKEN_ERROR_EXIST);
            }
        }

        return $next($request);

    }
}
